import java.beans.Statement;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.freeswitch.*;
import org.freeswitch.swig.*;

/**
 * 
 * @author tarun
 *	This is used for handling all the queries related to IVRS. 
 */
public class Optimized implements FreeswitchScript, DTMFCallback, HangupHook{

	/**
	 * This denotes the active session with the user.
	 */
	private JavaSession Session=null;
	
	/**
	 * This represents the Phone Number in String Format.
	 */
	private String phonenum=null;
	
	/**
	 * This string represents the directory where all the .wav files are saved.
	 */
	private String aosd="usr/local/freeswitch/scripts/IIITD/sounds/niharika"; 
	
	private int GlobalCnt=0;
	private String input="";
	private String Ending="N";
	private FileWriter inputStream=null;
	private SimpleDateFormat sessid=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private String rep="N";
	private Connection Con; 
	private String Role;
	private String sd="/home/ivr/media/WS";
	
	@Override
	public void run(String sessionUuid, String arg1) {

        Session = new JavaSession(sessionUuid);
        phonenum=Session.getVariable("caller_id_number");
        try {
			Con=DriverManager.getConnection("localhost", "ivr", "ivr");
		} catch (SQLException e) {
			
			e.printStackTrace();
		} 
		
	}

	@Override
	public String onDTMF(Object arg0, int arg1, String arg2) {
		
		return null;
	}

	@Override
	public void onHangup() {
		
		
	}
	
	/**
	 * This Function is used for validating the caller. 
	 * @throws SQLException if any SQL Table Not Found or any other error related to SQL Databases.
	 */
	public void validate_caller() throws SQLException
	{
		Session.execute("set_audio_level", "write 1");
		
		while(Session.ready()==true)
		{
			java.sql.Statement query7=Con.createStatement();
			query7.executeUpdate("update I_Caller set question = 'N' where Phone_no = 1003 ");
//			freeswitch.console_log("info", );
			ResultSet Set;
			Set=query7.executeQuery("select * from I_Caller where Phone_no = '" + phonenum + "'");
			String Name=Set.getString(1);
			String Number=Set.getString(2);
			if(Name!=null && Number!="N")
				Role="guest";
			if(Name==null || Number==null)
			{
				Role="guest";
				query7.executeUpdate("insert into I_Caller(Phone_no,question) values (" + phonenum + ",'N')");
			}
			if(Name!=null && Number=="Y")
			{
				Role="aspirant";
			}
			Set=query7.executeQuery("select * from Responder where responder_no = '" + phonenum +"'");
//			freeswitch.console_log("info", );
			Name=Set.getString(1);
			Number=Set.getString(2);
			if(Name==null || Number==null)
			{
				Role="guest";
			}
			else
				Role="responder";
		}
	}
	
	/**
	 * This is used for initial response to the user/caller
	 * @throws SQLException if any SQL Table Not Found or any other error related to SQL Databases. 
	 * @throws IOException  if there is any error while reading the .wav file
	 */
	public void responder_menu() throws SQLException, IOException 
	{
		ResultSet Set;
		Session.answer();
		Session.setAutoHangup(false);
		read(aosd.concat("/prompts/welcome.wav"),200);
		read(aosd.concat("/prompts/option.wav"),200);
		java.sql.Statement query=Con.createStatement();
		Set=query.executeQuery("SELECT * FROM R_ques_ans WHERE responder_ans is NULL");
		String x=null;
		String name=Set.getString(1);
		if(name==null)
			read(aosd.concat("/prompts/noQ.wav"),200);
		else
		{
			while(Set.next())
			{
//				freeswitch.consoleLog();
				String dir_Q=sd + "/Q/" +Set.getString(2) +"";			
				int z=playfile(dir_Q);
				if(z==2)
				{
					String h=record_my_question(Set.getString(1));
				}
				else
				{
					if(z==9)
						break;
				}
			}
		}
		
	}
	
	public void guest_menu(int index)
	{
		
	}
	
	public String Nodes(int index)
	{
		inputStream =new FileWriter("logfile.txt");
		java.sql.Statement query=Con.createStatement();
		ResultSet Set;
		String key="";
		String digits="";
		if(input=="")
		{
			GlobalCnt=GlobalCnt+1;
			if(GlobalCnt==10)
			{
//				freeswitch.consoleLog();
				hangup();			// write this function
			}
		}
		if(index==1)
		{
			Set=query.executeQuery("SELECT * FROM Nodes WHERE level_id like '"+ input + "_' and level_id != 42 order by level_id");
		}
		else
			Set=query.executeQuery("SELECT * FROM Nodes WHERE level_id like '"+ input + "_' order by level_id");
//		freeswitch.consoleLog(arg0, arg1);
		int i=0;
		if(Set.getString(1)==null)
		{
			read(aosd+"/prompts/invalid_option.wav",200);
		}
		int j=input.length();		//doubt in this line j=input.length(input)
		sessid.setTimeZone(TimeZone.getTimeZone("UTC"));
		String Time=sessid.format(new Date()); 
		inputStream.write(Time+ "\t" + Session.getVariable("caller_id_number")+ "\t" + Session.getVariable("destination_number")+ "\t" + Time+"\t"+ "Invalid Option at Node id"+ "\t"+ input+"\n"); // I guess there might be an error in this line bcoz I m using Time twice. 
		input=input.substring(1,j-1);
		return "*";
		
		while(Set.next())
		{
			if(Set.getString(1)== input+"*")
			{
				String flag1=checkfunc(Set.getString(1),Set.getString(2),Set.getString(3));
				if(flag1=="0" && Ending=="N")
				{
	//				freeswitch.consoleLog
					while(true)
					{
						String Filename= aosd+"/menu/"+Set.getString(2);
						read(Filename,200);
						read(aosd+"/prompts/repeat_response.wav",2000);
						int f=use();
						if(f==5)
						{
							
						}
						else
							return "0";
					}
				}
				return flag1;
			}
			String Filename=aosd+ "/menu/"+ Set.getString(2);
//			freeswitch.consoleLog();
			read(Filename,0);
			read(aosd+"/Digits/"+i+".wav",1500);
			key=use();
//			freeswitch.consolelog();
			if(key!="")
			{
				i+=1;
				rep="N";
				return key;
			}
			else
			{
				i+=1;
				rep="Y";
			}
		}
		if(rep=="Y")
		{
			read(aosd+"/prompts/no_option.wav",100);
			return "*";
		}
	}
	
	public String checkfunc(String func,String id,String tag)
	{
		return "0";
	}
	
	public void speak(String message,String method)
	{
		Session.execute("set_audio_level","write 4");
		Session.say(message, "en", "number", method);
		Session.execute("set_audio_level","write 0");
	}
	
	public void get_result()
	{
		
	}
	
	public String get_faq() throws IOException
	{
		int no_faq=3;
		for(int i=0;i<=no_faq;i++)
		{
			while(true)
			{
//				freeswitch.consoleLog	
				read(aosd+"/Q/Q"+ i + ".wav",2000);
				String j=use();
				if(j=="")
				{
					while(true)
					{
//						freeswitch.consoleLog
						read(aosd+"/prompts/response.wav",200);
						read(aosd+"/A/A"+i+".wav",2000);
						String h=use();
						if(h=="5")
						{
							
						}
						else
						{
							if(h=="0" || h=="9" || h=="8")
							{
								return h;
							}
							else 
								break;
						}
					}
					if(i<no_faq)
					{
						read(aosd+"/prompts/nextQ.wav",500);
					}
					break;
					
				}
				else
				{
					if(j=="5")
					{
						
					}
					else
					{
						if(j=="0" || j=="9" || j=="8")
							return j;
						else
							read(aosd+"/prompotd/nextQ.wav",500);
						
					}
				}
			}
		}
		Ending="Y";
		return "0";
	}
	
	public int playfile(String file_name)
	{
		return 0;
	}
	
	public String record_my_question(String Qid)
	{
		inputStream=new FileWriter("logfile.txt");	//overwrite whatever has been written in above functions(problem :()
		SimpleDateFormat sessid1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		sessid1.setTimeZone(TimeZone.getTimeZone("UTC"));
		String Time=sessid.format(new Date()); 
		String partfilename= Time+".mp3";
		String filename;
		if(Role=="guest" || Role=="aspirant")		
		{
			filename=sd+"/Q/"+partfilename;
		}
		else
			filename=sd+"/A"+partfilename;
		int maxlength=60000;
		String d;
		do{
			d=use();
			if(d==GLOBAL_MENU_MAINMENU)	//can't even find this GLOBAL_MAIN_MAINMENU 
				return d;
			Session.execute("playback", "tone_stream://%(500,0,620)");
//			freeswitch.consoleLog()
			inputStream.write(Time+"\t"+Session.getVariable("caller_id_number")+ "\t" + Session.getVariable("destination_number")+ "\t"+Time+"\t"+"Record"+"\t" +filename+"\n");//might be some problem with this time 
			Session.execute("record",filename+" "+ maxlength+" 100 5");
			d=use();
			if(Session.ready()==false)
			{
		//		freeswitch.consoleLog();
				hangup();
				break;
			}
			if(d==GLOBAL_MENU_MAINMENU)
			{
//				Has to Delete File
				return d;
			}
			int review_cnt=0;
			while(d!= GLOBAl_MENU_MAINMENU && d!="1" && d!="2" && d!="3")
			{
				read(aosd+"/prompts/recording_check.wav",1000);
				read(filename,1000);
				read(aosd+"/prompts/not_satisfied.wav",2000);
				sleep(6000);		//Not defined this function
				d=use();
				if(Session.ready()==false)
				{
//					freeswitch.consoleLog();					
					hangup();
				}
			}
			if(d!="1" && d!="2")
			{
//				Has to delete file
				if(d==GLOBAL_MENU_MAINMENU)
					return d;
				else if(d=="3")
				{
					read(aosd+"/prompts/message_cancel.wav",500);
					Ending="Y";
					return "0";
				}
			}
			if(Session.ready()==false)
			{
//				freeswitch.consoleLog()
				hangup();
				int done=1;			// Can't find where u have defined done
				break;
			}
		}while(d=="5");
		if(Session.ready()==true && Role="responder")
		{
			java.sql.Statement query1=Con.createStatement();
			query1.executeUpdate("update R_ques_ans set responder_ans='" + partfilename + "' where user_id = " + Qid + "");
			read(aosd+"/prompts/response_back.wav",100);
			query1.executeUpdate("insert into Replies (reply_text) values ('" + partfilename + "')");
			query1.executeUpdate("update Mapping set reply_id = (select reply_id from Replies where reply_text = '"+ partfilename +"') where question_id = (select question_id from Questions where question_text= (select caller_ques from R_ques_ans where responder_ans='"+ partfilename +"') ) and reply_id is NULL");
			ResultSet Set=query1.executeQuery("select Phone_no from R_ques_ans where responder_ans = '" + partfilename +"'");
//			freeswitch.consoleLog();
			if(Set.getString(1)!=null)
				send_sms("Your query has been resolved.Please Dial 09013182123 or 011-25099209 to listen the rrsponse. --Sent by Winter School 2011, IIIT Delhi",Set.getString(1));
			Ending="N";
			return "0";

			
			
		}
//		DataBase Updation for new User
		if(Session.ready()==true && (Role == "aspirant" || Role=="guest"))
		{
			java.sql.Statement query1=Con.createStatement();
			query1.executeUpdate("insert into R_ques_ans (caller_ques, Phone_no) values('" + partfilename + "','" + phonenum + "')");
			query1.executeUpdate("insert into Mapping values((select question_id from Questions where question_text='" + partfilename + "'),NULL)");
			query1.executeUpdate("update I_Caller set question='Y' where Phone_no='" + phonenum + "'");
			ResultSet Set=query1.executeQuery("select responder_no from Responder");
//			freeswitch.consoleLog();
			while(Set.next())
			{
				send_sms(" A new query has arrived for you. Dial 09013182123 to answer the query --Sent By Winter School 2011, IIIT Delhi",Set.getString(1));
			}
			Ending="N";
			return "0";
		}
	}
	
	public void send_sms(String message,String number)
	{
		
	}
	
	public String play_my_response() throws SQLException, IOException 
	{
		
		java.sql.Statement query3=Con.createStatement();
//		freeswitch.console_log("info", );
		String key="";
		ResultSet Set;
		Set=query3.executeQuery("select responder_ans from R_ques-ans where Phone no = '" + phonenum + "' and responder_ans is not NULL ");
		if(Set.getString(1)==null)
			read(aosd+"/prompts/noresponse.wav",200);
		else
		{
			read(aosd+"/prompts/exitmain.wav",200);
			while(Set.next())
			{
				read(aosd+"/prompts/response.wav",200);
				String dir=sd+"/A"+Set.getString(1);		//could not find sd anywhere in the file
				while(true)
				{
					read(dir,500);
					read(aosd+"/prompts/repeat_response.wav",3000);
					String key=use();
					if(key=="5")
					{
						
					}
					else
					{
						if(key=="9" || key=="0" || key=="8")
						{
							Ending="Y";
							return key;
						}
						break;
					}
				}
			}
		}
		return "0";
	}
	
	public void select_voice()
	{
		
	}
	
	/*-------------------------------
	 * Functions Defined in Common and Path
	 ------------------------------*/
	public void read(String file, int delay) throws IOException
	{
		FileWriter logfile=null;
		logfile =new FileWriter("logfile.txt");
	//	logfile.write(str)
	//	has to write remaining code
		Session.read(1, 1, file,delay,"#");
		
	}
	
}
